package me.shiqiang.im;

import com.tst.common.utils.DateUtils;
import me.shiqiang.im.service.StatisticsClient;
import me.shiqiang.im.statistics.MsgCount;
import me.shiqiang.im.vo.MsgStatisticsVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by John on 2018/1/29
 */
@Component
public class MsgStatisticsTask {

    @Autowired
    StringRedisTemplate redisTemplate;


    private static final Logger logger = LoggerFactory.getLogger(MsgStatisticsTask.class);

    private static boolean processFlag = false;

    @Value("${server.id}")
    private String id;

    @Autowired
    StatisticsClient statisticsClient;
    /**
     * 每小时执行一次
     */
//    @Scheduled(cron = " 0 */1 * * * ?") //测试用，每分钟执行
    @Scheduled(cron = "0 0 */1 * * ?")
    public void run() {
        try {
            if (processFlag) {
                logger.warn(String.format("[%s]上一次任务还在执行,本次跳过", this.getClass().getSimpleName()));
                return;
            }
            processFlag = true;

            process();
        } catch (Exception e) {
            logger.error("MsgStatisticsTask run error", e);
        } finally {
            processFlag = false;
        }
    }

    /**
     * IM聊天数统计task
     */
    private synchronized void process() {
        try {
            MsgStatisticsVo vo = new MsgStatisticsVo();
            String date = DateUtils.format(new Date(), new SimpleDateFormat("yyyy:MM:dd:HH").toPattern());
            MsgCount msgCount = MsgCount.getInstance();
            vo.setP2pCount(msgCount.getP2pMsgCount().longValue());
            vo.setGroupCount(msgCount.getGroupMsgCount().longValue());
            vo.setTotalMsgCount(msgCount.getP2pMsgCount().addAndGet(msgCount.getGroupMsgCount().longValue()));
            vo.setServerId(id);
            vo.setDate(date);
            msgCount.resetGroupCount();
            msgCount.resetP2pCount();
            statisticsClient.saveMsgStatistics(vo);
//            System.out.println(JSONUtils.toJSON(redisTemplate.opsForZSet().reverseRangeWithScores("Msg", 0L, 99999999L)));
        } catch (Exception e) {
            logger.error("MsgStatisticsTask process error", e);
        }
    }
}
